package com.snowy.hidden.redisdic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSplitter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fhs.trans.service.impl.DictionaryTransService;
import com.snowy.redis.RedisStaticUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

/**
 *  字典翻译服务
 */
@Component
public class DictionaryTransRedis extends DictionaryTransService {

    private static  Map<String, String> hashMap;

    public static  void initHashmap(){
        if (ObjectUtil.isEmpty(hashMap)){
            hashMap=new HashMap<>();
            Set<String> entries = RedisStaticUtil.keys("trans:*");
            entries.stream().forEach(key->{
                String value = RedisStaticUtil.getStr(key).replace("\"", "");
                String  key1 = key.replace("trans:", "");
                System.out.println(key1+"==="+value);
                hashMap.put(key1,value);

            });

        }
    }

    /**
     * 通过分组编码和子值获取字典翻译值
     *
     * @Params: dictGroupCode – 字典分组编码
     * @Params: childValue – 字典子值
     */
    public AtomicReference<String> getChildKeyTransValue(String dictGroupCode, String childValue) {

        AtomicReference<String> keyvalue=new AtomicReference<>();
        hashMap.keySet().stream().forEach(key->{
            List<String> tempKeyList = StrSplitter.split(key, '_', 0, true, true);
            String endkey=tempKeyList.get(tempKeyList.size()-1);//新的key
            tempKeyList.remove(endkey);
            String tempdictGroupCode= CollUtil.join(tempKeyList, "_");
            if(StrUtil.equals(tempdictGroupCode,dictGroupCode)){
                if (StrUtil.equals(hashMap.get(key), childValue)){
                    keyvalue.set(endkey);
                }
            }

        });
        return keyvalue;
    }
}
